package com.aau.edu;

import com.aau.edu.pojo.Author;
import com.aau.edu.pojo.Book;

import java.util.ArrayList;
import java.util.Optional;
import java.util.function.Supplier;

import static java.util.stream.Stream.ofNullable;

public class OptionalDemo01 {
    public static void main(String[] args) {
        //推荐直接使用ofNullable方法来创建Optional对象
        Optional<Object> o = Optional.ofNullable(null);
//        System.out.println(o);
        //以下写法就优雅的避免了空指针异常
//        Author author = getAuthor();
//        Optional<Author> authorOptional = Optional.ofNullable(author);
//        authorOptional.ifPresent((author1 -> System.out.println(author1.getName())));

        Optional<Author> authorOptional1 = getAuthorOptional();
        authorOptional1.ifPresent(author -> System.out.println(author.getName()));
        //安全获取值
        //orElseGet
//        authorOptional1.orElseGet(new Supplier<Author>() {
//            @Override
//            public Author get() {
//                return new Author();
//            }
//        });
        Author author = Optional.ofNullable(getAuthor()).orElseGet(() -> new Author(1L, "蒙多111", 33, "一个从菜刀中明悟哲理的祖安人", null));
        System.out.println(author.getName());//有值就返回原值，没有值的话就返回原来的默认值
        //orElseThrow
        //获取数据，如果数据不为空就能获取到该数据。如果为空则根据你传入的参数来创建异常抛出。
        Optional<Author> authorOptional = Optional.ofNullable(getAuthor());
        try {
            authorOptional.orElseThrow((Supplier<Throwable>) () -> new RuntimeException("author为空"));
            System.out.println(author.getName());
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        }
        System.out.println("---------------------------");
        //过滤
        //filter
        Optional<Author> authorOptional2 = Optional.ofNullable(getAuthor())
                .filter(author2 -> author2.getAge() > 18);
        authorOptional2.ifPresent(author1 -> System.out.println(author1.getName()));
        System.out.println("---------------------------");
        //数据转换
        //map
        Optional<Author> authorOptional3 = Optional.ofNullable(getAuthor());
        authorOptional3.map(author2 -> author2.getBooks())
                .ifPresent(books -> System.out.println(books));

    }

    private static Optional<Author> getAuthorOptional() {
        ArrayList<Book> books = new ArrayList<>();
        books.add(new Book(1L, "刀的两侧是光明与黑暗", "哲学,爱情", 88, "用一把刀划分了爱恨"));
        //数据初始化
        Author author = new Author(1L, "蒙多", 33, "一个从菜刀中明悟哲理的祖安人", books);
//        return Optional.ofNullable(author);
        return author == null ? Optional.empty() : Optional.of(author);
    }

    private static Author getAuthor() {
        ArrayList<Book> books = new ArrayList<>();
        books.add(new Book(1L, "刀的两侧是光明与黑暗", "哲学,爱情", 88, "用一把刀划分了爱恨"));
        //数据初始化
        Author author = new Author(1L, "蒙多", 33, "一个从菜刀中明悟哲理的祖安人", books);
        return author;
    }
}
